import React, { Component } from "react";
import { Redirect } from "react-router-dom";
import login from "../hooks/loginInfo";
import PageHeader from "../components/PageHeader";
import "../assets/css/OrderDetail.css";
import ShopBagItem from "../components/ShopBagItem";
import Popup from "../components/Popup";
import AddressItem from "../components/AddressItem";
import { errorToast, successToast } from "../components/Toast";
import Loading from "../components/Loading";

class OrderDetail extends Component {
  constructor(props) {
    super(props);

    this.state = {
      token: null,
      orderList: null,
      totalNum: null,
      totalPrice: null,
      showAddress: false,
      addressList: null,
      currentAddress: null,
    };
    this.toggleShowAddress = this.toggleShowAddress.bind(this);
    this.ToAddAddress = this.ToAddAddress.bind(this);
    this.selectedAddress = this.selectedAddress.bind(this);
    this.account = this.account.bind(this);
  }

  account() {
    if (!this.state.currentAddress) {
      errorToast("请选择收货地址")
    } else {
      this.$axios
        .post("/pay", {
          tokenString: this.state.token,
          phone: this.state.currentAddress.tel,
          address:
            this.state.currentAddress.province +
            this.state.currentAddress.city +
            this.state.currentAddress.county +
            this.state.currentAddress.addressDetail,
          receiver: this.state.currentAddress.name,
          sids: JSON.stringify(this.props.location.query.sid),
        })
        .then((res) => {
          successToast(res.data.msg);
          this.props.history.push("/myOrder");
        });
    }
  }
  selectedAddress(item) {
    this.setState({
      currentAddress: item,
    });
    this.toggleShowAddress();
  }

  ToAddAddress() {
    this.props.history.push("/addAddress");
  }
  toggleShowAddress() {
    this.setState({
      showAddress: !this.state.showAddress,
    });
  }

  componentWillMount() {
    var loginInfo = login();
    this.setState({
      token: loginInfo.token,
    });
    if (this.props.location.query) {
      this.$axios
        .get("/commitShopcart", {
          params: {
            tokenString: loginInfo.token,
            sids: JSON.stringify([...this.props.location.query.sid]),
          },
        })
        .then((res) => {
          var num = 0;
          var price = 0;
          res.data.result.forEach((item) => {
            num += item.count;
            price += item.count * item.price;
          });
          this.setState({
            orderList: res.data.result,
            totalNum: num,
            totalPrice: price,
          });
        });
      this.$axios
        .get("/findAddress", {
          params: {
            tokenString: loginInfo.token,
          },
        })
        .then((res) => {
          this.setState({
            addressList: res.data.result,
          });
          res.data.result.findIndex((item) => {
            if (item.isDefault === 1) {
              this.setState({
                currentAddress: item,
              });
            }
            return item.isDefault === 1;
          });
        });
    } else {
      this.props.history.push("/");
    }
  }

  render() {
    return this.props.location.query ? (
      this.state.orderList ? (
        <div className="OrderDetail">
          <PageHeader>
            <span slot="title">提交订单</span>
          </PageHeader>
          <div className="OrderDetail_content">
            <div className="OrderDetail_address">
              <div className="selected_title" onClick={this.toggleShowAddress}>
                <span>选择收货地址</span>
                <i></i>
              </div>
              {this.state.currentAddress && (
                <div className="address_detail">
                  <div>
                    <span className="address_detail_name">
                      {this.state.currentAddress.name}
                    </span>
                    <span className="address_detail_tel">
                      {this.state.currentAddress.tel}
                    </span>
                  </div>
                  <div>
                    <span>{this.state.currentAddress.province}</span>
                    <span>{this.state.currentAddress.city}</span>
                    <span>{this.state.currentAddress.county}</span>
                    <span>{this.state.currentAddress.addressDetail}</span>
                  </div>
                </div>
              )}
            </div>
            <div className="OrderDetail_order">
              <div className="order_title">订单信息</div>
              <ul className="order_list">
                {this.state.orderList.map((item) => {
                  return <ShopBagItem key={item.pid} item={item}></ShopBagItem>;
                })}
              </ul>
              <span className="ball_left"></span>
              <span className="ball_right"></span>
            </div>
            <div className="OrderDetail_total">
              <span>共计 {this.state.totalNum} 件商品</span>
              <span>合计 ￥{this.state.totalPrice}</span>
            </div>
          </div>
          <button className="account" onClick={this.account}>
            立即结算
          </button>
          {this.state.showAddress && (
            <Popup radius="10px 10px 0 0" closePopup={this.toggleShowAddress}>
              <p className="popup_title">选择收货地址</p>
              {this.state.addressList && (
                <ul className="address_list">
                  {this.state.addressList.map((item) => {
                    return (
                      <AddressItem
                        check={true}
                        currentAddress={this.state.currentAddress}
                        onClick={this.selectedAddress}
                        key={item.id}
                        item={item}
                      ></AddressItem>
                    );
                  })}
                </ul>
              )}
              <button className="popup_addbtn" onClick={this.ToAddAddress}>
                新增地址
              </button>
            </Popup>
          )}
        </div>
      ) : <Loading></Loading>
    ) : (
      <Redirect to="/"></Redirect>
    );
  }
}

export default OrderDetail;
